package com.redrose.videodemo.runnabletask;

import com.redrose.videodemo.utils.EventBusMessage;
import com.redrose.videodemo.utils.PathUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Desc:
 * Author: RedRose
 * Date: 2019/3/30
 * Email: yinsxi@163.com
 */

public class DownloadDouyinVideo implements Runnable {
private String needDownloadUrl;

    public DownloadDouyinVideo(String needDownloadUrl) {
        this.needDownloadUrl = needDownloadUrl;
    }

    @Override
    public void run() {
        try {
//          URL url = new URL("https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0300fc70000bidioitm8tc3rf5f3g9g&line=0");
            URL url = new URL("https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0300fc70000bidioitm8tc3rf5f3g9g&line=0");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(6000);
            urlConnection.setUseCaches(false);
            urlConnection.connect();
            String adress = urlConnection.getHeaderField("Location");
            downloadNoWater(adress);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void downloadNoWater(String urlReal) throws IOException {
        File file = new File(PathUtil.getAppPicPath() + System.currentTimeMillis() + ".mp4");
        if (!file.exists()) {
//            file.mkdir();
            file.createNewFile();
        }
        FileOutputStream fos = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlReal);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(6000);
            urlConnection.setUseCaches(false);
            urlConnection.setDoInput(true);
            fos = new FileOutputStream(file);
            byte[] byres = new byte[1024];
            urlConnection.connect();
            int len;
            inputStream = urlConnection.getInputStream();
            while ((len = inputStream.read(byres)) != -1) {
                fos.write(byres,0,len);
            }
            fos.flush();
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.MSG_TYPE_GET_DOUYIN_DOWNLOAD_FINSH));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
